/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package boundary.registration;

import com.toedter.calendar.JDateChooser;
import control.Application;
import entity.Custody;
import entity.Sample;
import java.awt.BorderLayout;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import org.joda.time.DateTime;

/**
 *
 * @author Juan
 */
public class DCustodyRegistration extends javax.swing.JDialog {
    
    private boolean successful = false;
    private Custody newCustody;
    private JDateChooser dateChooser;
    
    public static final int LEFTOVER_DISPOSAL = 0;
    public static final int STORAGE = 1;
    public static final int DISPOSAL = 2;
    
    private static final String LEFTOVER_DISPOSAL_TITLE = "Registrar Devolución de Sobrantes";
    private static final String STORAGE_TITLE = "Registrar Almacenamiento";
    private static final String DISPOSAL_TITLE = "Registrar Disposición de Muestra";
    
    private static final String LEFTOVER_DISPOSAL_DATE = "Fecha de devolución de sobrantes:";
    private static final String STORAGE_DATE = "Fecha de almacenamiento:";
    private static final String DISPOSAL_DATE = "Fecha de disposición de muestra:";
    
    private static final String REGISTER_LEFTOVER_DISPOSAL = "Registrar devolución de sobrantes";
    private static final String REGISTER_STORAGE = "Registrar almacenamiento";
    private static final String REGISTER_DISPOSAL = "Registrar disposición de muestra";

    /**
     * Creates a new dialog for custody registration.
     *
     * @param parent the parent window.
     * @param modal is this window modal.
     * @param currentSample the sample which custody will be registered.
     * @param mode a constant flag found in the DCustodyRegistration class.
     */
    public DCustodyRegistration(java.awt.Frame parent, boolean modal, Sample currentSample, int mode) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        Date now = new Date();
        dateChooser = new JDateChooser(now);
        dateChooser.setMaxSelectableDate(now);
        PDatePicker.add(dateChooser, BorderLayout.NORTH);
        
        Float amountLeft = amountLeft(currentSample);
        SpinnerNumberModel model = new SpinnerNumberModel();
        model.setMaximum(amountLeft);
        model.setMinimum(0f);
        model.setValue(amountLeft);
        model.setStepSize(1f);
        SAmount.setModel(model);
        LAmountLeft.setText("de " + amountLeft + " gramos.");
        
        String title = "", dateLabel = "", registerLabel = "";
        if (mode == LEFTOVER_DISPOSAL) {
            title = LEFTOVER_DISPOSAL_TITLE;
            dateLabel = LEFTOVER_DISPOSAL_DATE;
            registerLabel = REGISTER_LEFTOVER_DISPOSAL;
        } else if (mode == STORAGE) {
            title = STORAGE_TITLE;
            dateLabel = STORAGE_DATE;
            registerLabel = REGISTER_STORAGE;
        } else if (mode == DISPOSAL) {
            title = DISPOSAL_TITLE;
            dateLabel = DISPOSAL_DATE;
            registerLabel = REGISTER_DISPOSAL;
        }
        setTitle(title);
        LDate.setText(dateLabel);
        BRegister.setText(registerLabel);
        LSample.setText(currentSample.toString());
    }
    
    private Float amountLeft(Sample sample) {
        Float amountLeft = sample.getQuantity();
        Custody leftoverDisposal = sample.getLeftoverDisposal();
        Custody disposal = sample.getDisposal();
        
        if (leftoverDisposal.isRegistered()) {
            amountLeft -= leftoverDisposal.getAmount();
        }
        
        if (disposal.isRegistered()) {
            amountLeft -= disposal.getAmount();
        }
        
        return amountLeft;
    }

    public Custody getNewCustody() {
        setVisible(true);
        if (successful) {
            return newCustody;
        }
        return null;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LSample = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        PDatePicker = new javax.swing.JPanel();
        LDate = new javax.swing.JLabel();
        SAmount = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TAComments = new javax.swing.JTextArea();
        BRegister = new javax.swing.JButton();
        BCancel = new javax.swing.JButton();
        LAmountLeft = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        LSample.setText("jLabel1");

        jLabel1.setText("Cantidad:");

        PDatePicker.setLayout(new java.awt.BorderLayout());

        LDate.setText("jLabel2");

        jLabel2.setText("Comentarios:");

        TAComments.setColumns(20);
        TAComments.setRows(5);
        jScrollPane1.setViewportView(TAComments);

        BRegister.setText("jButton1");
        BRegister.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegisterActionPerformed(evt);
            }
        });

        BCancel.setText("Cancelar");
        BCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelActionPerformed(evt);
            }
        });

        LAmountLeft.setText("jLabel3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PDatePicker, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(LSample)
                            .addComponent(jLabel1)
                            .addComponent(LDate)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BRegister)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BCancel))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(SAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LAmountLeft)))
                        .addGap(0, 163, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LSample)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(LDate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(LAmountLeft))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BRegister)
                    .addComponent(BCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelActionPerformed
        setVisible(false);
    }//GEN-LAST:event_BCancelActionPerformed

    private void BRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegisterActionPerformed
        newCustody = new Custody();
        
        Date date = dateChooser.getDate();
        if (date == null) {
            JOptionPane.showMessageDialog(this, "Por favor seleccione la fecha de almacenamiento.",
                    "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        newCustody.setDate(new DateTime(date.getTime()));
        
        newCustody.setComments(TAComments.getText());
        newCustody.setResponsible(Application.CURRENT_EMPLOYEE);
        
        Float amount = (Float) SAmount.getValue();
        if (amount == 0) {
            int option = JOptionPane.showConfirmDialog(this, "La cantidad de muestra a registrar es cero. "
                                            + "¿Está seguro de que desea continuar?",
                                            "Advertencia", JOptionPane.YES_NO_OPTION,
                                            JOptionPane.WARNING_MESSAGE);
            if (option == JOptionPane.NO_OPTION) {
                return;
            }
        }
        newCustody.setAmount(amount);
        newCustody.setStatus(true);
        successful = true;
        setVisible(false);
    }//GEN-LAST:event_BRegisterActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BCancel;
    private javax.swing.JButton BRegister;
    private javax.swing.JLabel LAmountLeft;
    private javax.swing.JLabel LDate;
    private javax.swing.JLabel LSample;
    private javax.swing.JPanel PDatePicker;
    private javax.swing.JSpinner SAmount;
    private javax.swing.JTextArea TAComments;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
